/*
 * @Author: your name
 * @Date: 2021-05-31 14:19:36
 * @LastEditTime: 2021-05-31 17:34:14
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bazai_island_api\core\init.js
 */

const requireDirectory = require("require-directory")
const Router = require('koa-router')
const config = require("../config/config.js")

class InitManager {
    constructor(){}
    static initCore(app) {
        // 入口方法
        InitManager.app = app
        InitManager.initLoadRouters()
        InitManager.loadHttpException()
        InitManager.loadConfig()
    }

    static initLoadRouters() {
        // process.cwd() 返回当前文件夹
        const apiDirectory = `${process.cwd()}/app/api`
        requireDirectory(module, apiDirectory, {
            visit: whenLoadModule
        })

        function whenLoadModule(obj) {
            if (obj instanceof Router) {
                InitManager.app.use(obj.routes())
            }
        }
    }

    static loadHttpException() {
        const errors = require('./http-exception.js')
        global.errs = errors
    }
    
    static loadConfig(path = '') {
        const configPath = path || process.cwd() + '/config/config.js'
        const config = require(configPath)
        global.config = config
    }
}

module.exports = InitManager
